#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

enum
{
    ARGU_ERROR = 1,
    SOCK_ERROR,
    BIND_ERROR,
    RECV_ERROR
};

// ./client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:\n\t" << argv[0] << " [ip] [port]\n";
        return ARGU_ERROR;
    }

    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];
    LOG(DEBUG, "ip : %s , port : %d\n", ip.c_str(), port);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "create socket fail, exit code : %d\n", SOCK_ERROR);
    }
    LOG(INFO, "create socket success\n");

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t serlen = sizeof(server);

    std::string s_buffer;
    char buffer[1024];
    while (true)
    {
        std::cout << "Please Enter# ";
        std::getline(std::cin, s_buffer);
        ssize_t n = sendto(sockfd, s_buffer.c_str(), sizeof(s_buffer), 0, (sockaddr *)&server, serlen);

        LOG(INFO, "client send query success : %s\n", s_buffer.c_str());
        
        sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t plen = sizeof(peer);
        n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&peer, &plen);
        if (n < 0)
        {
            LOG(ERROR, "recv fail, exit code : %d", RECV_ERROR);
        }
        else if (n > 0)
        {
            buffer[n] = 0;
            LOG(DEBUG, "n = %d\n", n);
            LOG(DEBUG, "client get answer# %s in chinese is %s",s_buffer.c_str(), buffer);
        }
        else if (n == 0)
        {
            break;
        }
    }

    return 0;
}